#include "ImageProcessor.h"
#include "afterdetect.h"
#include "configmanager.h"
#include "detectcachemodel.h"
#include "errordialogmanager.h"
#include "imagesavemanager.h"
#include "imagesavethread.h"
#include "kcentergreedyint8.h"
#include "pccore.h"
#include "tools.h"
#include <QDir>
#include <QRandomGenerator>

ImageSaveManager::ImageSaveManager(QObject* parent)
    : QObject(parent), sequenceNumber(0) {

    QDir dir(saveDir);
    qInfo() << "ImageSaveManager save :" << dir;
    if (!dir.exists()) {
        dir.mkpath("."); // 创建目录及其所有父目录
    }
    connect(&ConfigManager::getInstance(), &ConfigManager::fileNameChanged, this, [this](){
        configName = ConfigManager::getInstance().ccnfigfileName();
    });
}

void ImageSaveManager::saveImage()
{
    qInfo() << "ImageSaveManager::saveImage";
    QString filePath = generateFilePath(1);
    qInfo() << "ImageSaveManager::saveImage :" << filePath;
    // 创建并启动保存线程
    cv::Mat save_image ;
    QString out;
    if ( ImageProcessor::getInstance().displayHistory_ == true )
    {

        save_image =
            DetectCacheModel::instance().getItemByID(
                                            DetectCacheModel::instance().currentCacheSeclectId()).preProgeressImage;
        out += QString("id[%1]:").arg(DetectCacheModel::instance().currentCacheSeclectId());
    }else
    {
        if(ImageProcessor::getInstance().captureImgMode() == ImageProcessor::RateTriggered)
        {
            save_image =
                ImageProcessor::getInstance().imgCardsLast.getStepImage(StepProcess::Reprogress);
        }
        else
        {
            save_image =
                AfterDetect::getInstance().lastCard.getStepImage(StepProcess::Reprogress);
        }
        out += QString("realTime:");
    }

    out += filePath;

    // save_image = PCcore::getInstance().lastCvImage;
    if(save_image.empty())
    {
        ErrorDialogManager::instance().showNonBlockingError("保存图片失败,图片为空", out);
        return;
    }
    // void *result = PCcore::getInstance().getpcFutre().detect(save_image);
    // saveBinaryData(result , 784*1536 , "embedding" );
    // KCenterGreedyInt8::instance().addEmbedding(result, 100);
    if (cv::imwrite(filePath.toStdString(), save_image)) {
        ErrorDialogManager::instance().showNonBlockingInfo("保存图片成功", out);
    } else {
        ErrorDialogManager::instance().showNonBlockingError("保存图片失败", out);
    }
}

ImageSaveManager& ImageSaveManager::getInstance() {
    static ImageSaveManager instance; // 单例实例
    return instance;
}

void ImageSaveManager::saveImage(const cv::Mat& image ,int id ,  float probability_) {
    if(isEnableSave())
    {
        // 生成保存文件的路径
        float randomValue = QRandomGenerator::global()->bounded(1.0f);

        // 根据概率判断是否执行保存操作
        if (randomValue <= probability() || probability_ == 1) {
            // 生成保存文件的路径
            QString ext = ".png";  // 可以根据需求扩展为不同格式
            QString filePath = generateFilePath(id);

            // 创建并启动保存线程
            ImageSaveThread* saveThread = new ImageSaveThread(image, filePath);

            // 连接保存完成的信号
            //connect(saveThread, &ImageSaveThread::imageSaved, this, &ImageSaveManager::imageSaved);

            // 启动线程
            saveThread->start();
        }
    }
}


QString ImageSaveManager::generateFilePath(int id) {
    // 获取当前时间戳（以毫秒为单位的时间）
    qint64 timeStamp = QDateTime::currentMSecsSinceEpoch();

    // 生成完整路径：时间戳_编号.ext
    QString fileName = QString("%1%2_%3%4").arg(configName)
                           .arg(timeStamp)
                           .arg(id)
                           .arg(ext);

    // 返回保存文件的完整路径
    return QDir(saveDir).filePath(fileName);
}
